package com.rdc.qingkou.ui;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.githang.statusbar.StatusBarCompat;
import com.rdc.qingkou.Application.MyApplication;
import com.rdc.qingkou.R;
import com.rdc.qingkou.adapter.MyFragmentStatePagerAdapter;
import com.rdc.qingkou.base.BaseActivity;
import com.rdc.qingkou.config.Constant;
import com.rdc.qingkou.presenter.OtherHomepagePresenter;
import com.rdc.qingkou.ui.iview.IOtherHomepageView;
import com.rdc.qingkou.utils.MyUtils;
import com.rdc.qingkou.view.fragment.OtherHomepageFragment;
import com.rdc.qingkou.vo.CardVO;
import com.rdc.qingkou.vo.UserVO;
import com.rdc.qingkou.widget.GalleryPageTransformer;
import com.rdc.qingkou.widget.MyViewPager;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class OtherHomepageActivity extends BaseActivity<OtherHomepagePresenter> implements IOtherHomepageView {

    private CircleImageView mHeadImage;
    private TextView mNameTextView;
    private TextView mSignatureTextView;
    private MyViewPager mViewPager;
    private List<OtherHomepageFragment> mOtherHomepageFragmentList = new ArrayList<>();
    private MyFragmentStatePagerAdapter<OtherHomepageFragment> mAdapter;
    private UserVO mUser;
    private ImageView mSubscribeImageView;
    private int mCurrentPage = 1;
    private boolean isUpdate = false;
    private boolean isLastPage = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.windowBackground), true);
        setContentView(R.layout.activity_other_homepage);
        mUser = (UserVO) getIntent().getSerializableExtra("user");
        initViews();
        if (MyUtils.isNetworkConnected(this)) {
            mPresenter.getUserInfo(mUser.getUserId());
            mPresenter.getSubscribeStatus(mUser.getUserId(), MyApplication.getUser().getUserId());
            mPresenter.sendGetCardRequest(mUser.getUserId(), mCurrentPage);
            isUpdate = true;
        } else {
            Toast.makeText(this, "无网络！", Toast.LENGTH_SHORT).show();
        }
    }

    private void sendGetCardRequest(int userId) {
        if (MyUtils.isNetworkConnected(this)) {
            mPresenter.sendGetCardRequest(userId, mCurrentPage);
            isUpdate = true;
        } else {
            Toast.makeText(this, "无网络！", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.clearDisposable();
    }

    @Override
    public OtherHomepagePresenter getInstance() {
        return new OtherHomepagePresenter();
    }

    private void initViews() {
        ImageButton backImageButton = (ImageButton) findViewById(R.id.other_homepage_back_imageButton);
        backImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        mHeadImage = (CircleImageView) findViewById(R.id.other_homepage_head_CircleImageView);
        mHeadImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent intent = new Intent(OtherHomepageActivity.this, PersonalInfoActivity.class);
//                startActivity(intent);
            }
        });
        mNameTextView = (TextView) findViewById(R.id.other_homepage_name_textView);
        mSignatureTextView = (TextView) findViewById(R.id.other_homepage_signature_textView);
        mSubscribeImageView = (ImageView) findViewById(R.id.other_homepage_subscribe_imageView);
        mSubscribeImageView.setClickable(false);
        mSubscribeImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MyUtils.isNetworkConnected(OtherHomepageActivity.this)) {
                    if (mUser.getSubsribeStatus()) {
                        //取消订阅
                        AlertDialog.Builder dialog = new AlertDialog.Builder(OtherHomepageActivity.this);
                        dialog.setMessage("确认不再关注此人?");
                        dialog.setCancelable(true);
                        dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mSubscribeImageView.setImageResource(R.drawable.button_subscribe_normal);
                                mPresenter.subscribe(mUser.getUserId(), MyApplication.getUser().getUserId());
                                mUser.setSubsribeStatus(false);
                            }
                        });
                        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        dialog.show();
                    } else {
                        //订阅
                        mPresenter.subscribe(mUser.getUserId(), MyApplication.getUser().getUserId());
                        mUser.setSubsribeStatus(true);
                        mSubscribeImageView.setImageResource(R.drawable.button_subscribe_pressure);
                    }
                } else {
                    Toast.makeText(OtherHomepageActivity.this, "无网络！", Toast.LENGTH_SHORT).show();
                }
            }
        });

        ConstraintLayout mRootLayout = (ConstraintLayout) findViewById(R.id.other_homepage_rootLayout);
        mRootLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return mViewPager.dispatchTouchEvent(motionEvent);
            }
        });

        mViewPager = (MyViewPager) findViewById(R.id.other_homepage_viewpager);
        mAdapter = new MyFragmentStatePagerAdapter<>(getSupportFragmentManager(), mOtherHomepageFragmentList);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setPageTransformer(false, new GalleryPageTransformer());
        mViewPager.setPageMargin(-80);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == mOtherHomepageFragmentList.size() && !isUpdate && !isLastPage) {
                    sendGetCardRequest(mUser.getUserId());
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void setUserInfo(UserVO userVO) {
        mUser = userVO;
        Glide.with(this).load(userVO.getHeadImageUrl()).into(mHeadImage);
        mNameTextView.setText(userVO.getNickName());
        mSignatureTextView.setText(userVO.getSignature());
    }

    @Override
    public void getUserInfoError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getSubscribeStatusError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void setSubscribeStatus(boolean status) {
        mSubscribeImageView.setClickable(true);
        mUser.setSubsribeStatus(status);
        if (status) {
            mSubscribeImageView.setImageResource(R.drawable.button_subscribe_pressure);
        } else {
            mSubscribeImageView.setImageResource(R.drawable.button_subscribe_normal);
        }
    }

    @Override
    public void updateCard(List<CardVO> cards) {
        isUpdate = false;
        if (cards != null) {
            int currentCardNum = mOtherHomepageFragmentList.size();
            if (cards.size() < Constant.CARD_NUM_OF_ONEPAGE) {
                isLastPage = true;
            } else {
                mCurrentPage++;
            }
            for (CardVO card : cards) {
                OtherHomepageFragment ohf = new OtherHomepageFragment();
                ohf.setCard(card);
                mOtherHomepageFragmentList.add(ohf);
            }
            mAdapter.notifyDataSetChanged(true);
        } else {
            isLastPage = true;
        }
    }

    @Override
    public void getCardError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void subscribeError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void subscribeSuccess(boolean status) {
        mUser.setSubsribeStatus(status);
        if (status) {
            mSubscribeImageView.setImageResource(R.drawable.button_subscribe_pressure);
        } else {
            mSubscribeImageView.setImageResource(R.drawable.button_subscribe_normal);
        }
    }
}
